package clientmgl;

import java.awt.Color;

import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import java.awt.event.MouseMotionListener;
import java.awt.geom.AffineTransform;
import java.io.DataOutputStream;
import java.io.IOException;
import java.util.ArrayList;

import javax.swing.JPanel;

import objects.SpetialFeature;
import objects.WorldObject;



import extra.Position;
import constants.*;

public class Inventory extends JPanel{
	
	ArrayList<WorldObject> listObjects = new ArrayList();
	ClientMGL clientMGL = null;
	DataOutputStream flujoSalida;
	
	PopUpInteraction popUp = new PopUpInteraction();
	
	private int state = Constants.WAIT_FOR_ACTION;
	private int objectID=-1;
	
	private int dx=0,dy=0;
	private int x=0,y=0;
	
	private int width=Constants.INVENTORY_WIDTH;
	private int height = Constants.INVENTORY_HEIGHT;
	
	private MainFrame frame;
	
	private int mouseY=0;
	
	public Inventory(DataOutputStream flujoSalida, MainFrame frame){
		this.flujoSalida=flujoSalida;
		this.frame=frame;
		listObjects = new ArrayList();
		setPreferredSize(new Dimension(Constants.INVENTORY_WIDTH,Constants.INVENTORY_HEIGHT));
		addMouseListener(new mouseListener());
		addMouseMotionListener(new mouseMotionListener());
	}
	
	@Override
	public void paint(Graphics g) {
		
		Graphics2D g2d = (Graphics2D) g;
		AffineTransform prev = g2d.getTransform();
		AffineTransform at =prev;
	
		//PARA LAS Y
		
		if((mouseY)>=frame.getHeight()-Constants.BORDER_TO_MOVE_PANEL){
			if((frame.getHeight()-dy-Constants.MOVE_PANEL_SPEED)<=height){
			//	System.out.println("estoy yendo hacia arriba");
				dy=dy-Constants.MOVE_PANEL_SPEED;
			}
			
		}
		if(mouseY<Constants.BORDER_TO_MOVE_PANEL){
			if((dy+Constants.MOVE_PANEL_SPEED)<=0){
			//	System.out.println("estoy yendo hacia abajo");
				dy=dy+Constants.MOVE_PANEL_SPEED;
			}
		}
		
				
		at=AffineTransform.getTranslateInstance(dx,dy);
		g2d.setTransform(at);
		
		int y=20;
		int x=10;
		g.setColor(Color.blue);
		height = frame.getHeight();
		//System.out.println("height "+height);
		if( (40+30)*(listObjects.size()) >height ){
			height=(40+30)*(listObjects.size());
		}
		//System.out.println("height1 "+height);
		g.fillRect(0, 0, width, height);
		g.setColor(Color.black);
		for(WorldObject w : listObjects){
			w.getImageObject().setPosition(new Position(x, y));
			paintBackgroundEquipedObject(g,w,x,y);
			g.drawImage(w.getImageObject().getMini(),x,y,null);
			y=y+w.getImageObject().getImageToShow().getHeight()+20;
			drawLife(w, g);
			
		}
		
		g2d.setTransform(prev);
	}
	
	private void drawLife(WorldObject object, Graphics g) {
		double currentLife=0;
		double totalLife=0;
		
		Object featureList [] = object.getListFeatures().toArray(); 
		
		for(int i=0;i<featureList.length;i++){
			SpetialFeature feature = (SpetialFeature) featureList[i];
			if(feature.getId()==ReferenceSpecialFeature.SPETIAL_FEATURE_LIFE){
				totalLife=feature.getValue();
			}
			if(feature.getId()==ReferenceSpecialFeature.SPETIAL_FEATURE_CURRENT_LIFE){
				currentLife=feature.getValue();
			}
		}
		
		if(totalLife==0){
			return;
		}
		int greenBar = (int)((currentLife*object.getImageObject().getImageToShow().getWidth())/totalLife);
		
		g.setColor(Color.red);
		g.fillRect((int)object.getImageObject().getPosition().getX(),(int)object.getImageObject().getPosition().getY()-10, object.getImageObject().getImageToShow().getWidth(), 5);
		
		g.setColor(Color.green);
		g.fillRect((int)object.getImageObject().getPosition().getX(),(int)object.getImageObject().getPosition().getY()-10, greenBar, 5);
		
		g.setColor(Color.black);
		
	}
	
	private void paintBackgroundEquipedObject(Graphics g, WorldObject w,int x, int y) {
		// to draw green rectangle
					SpetialFeature equiped = w.getFeature(ReferenceSpecialFeature.SPETIAL_FEATURE_OBJECT_EQUIPED);
				    if(equiped==null){
						return ;
					}
					if(equiped.getValue()==constants.Constants.FALSE){
						return;
					}
					g.setColor(Color.green);
					
					g.fillRect(x,(int)w.getImageObject().getPosition().getY(), w.getImageObject().getImageToShow().getWidth(), w.getImageObject().getImageToShow().getHeight());
	}


	
	
	
	private void askForAgentsFrom(int x, int y) {
		// TODO Auto-generated method stub
		
	}
	
	
	private void requestInventoryFromObject() {
		objectID = getObjectID(x, y);
		String message = new String();
		System.out.println("este es el id client "+objectID);
		message=Message.REQUEST_INVENTORY+System.getProperty("line.separator")+objectID;
		frame.setObjectInventoryId(objectID);
		try {
			flujoSalida.writeUTF(message);
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
	
	private int getObjectID(int x, int y) {
		for(WorldObject obj : listObjects){
			if(x >obj.getImageObject().getPosition().getX() && y >obj.getImageObject().getPosition().getY() && 
					x <obj.getImageObject().getPosition().getX()+obj.getImageObject().getImageToShow().getWidth() &&
					y< obj.getImageObject().getPosition().getY()+obj.getImageObject().getImageToShow().getHeight())
			{
				
				System.out.println("tengo el ID inventorias1212");
				return obj.getID();
			}
			
		}
		return -1;
	}
	
	
	public void setObjects(String [] str){
		listObjects= new ArrayList();
		
		
		for(int i=1;i<str.length;i++){
			listObjects.add(MainFrame.createObject(str[i]));
			//System.out.println("cree un objeto en la inventorya");
		}
		for(WorldObject w: listObjects){
			w.getImageObject().setImageToShow(ImagesSingleton.images[w.getObjectReference()]);
			w.getImageObject().setMini(ImagesSingleton.imagesMini[w.getObjectReference()]);
			//System.out.println("cree un objeto en la inventorya "+w.getImageObject().getImageToShow().getWidth());
		}
		
		
		
		repaint();
	}

	public ClientMGL getClientMGL() {
		return clientMGL;
	}

	public void setClientMGL(ClientMGL clientMGL) {
		this.clientMGL = clientMGL;
	}
	
	public void generatePopUp(String[] splt) {
		objectID=getObjectID(x,y);
		frame.generatePopUp(splt,x,y,objectID);
		
	}

	public void setState(int state) {
		this.state=state;
		
	}
	
	public void addObjectIdToParameterMessage(int x, int y) {
		for(WorldObject obj : listObjects){
			if(x >obj.getImageObject().getPosition().getX() && y >obj.getImageObject().getPosition().getY() && 
					x <obj.getImageObject().getPosition().getX()+obj.getImageObject().getImageToShow().getWidth() &&
					y< obj.getImageObject().getPosition().getY()+obj.getImageObject().getImageToShow().getHeight())
			{
				
				System.out.println("ENCONTRE EL OBJETOOOOOOOOO "+obj.getID());
				//parametersMessage=parametersMessage+"/"+obj.getID();
				frame.setParametersMessage(frame.getParametersMessage()+"/"+obj.getID());
				return;
			}
			
		}
		System.out.println("NO HAY OBJETO SELECCIONADO");
		frame.getParametersStack().push(constants.Constants.PARAMETER_OBJECT);
		
	}
	
	public void sendParametersToAgent() {
		
		System.out.println("Tengo todos los parametros para enviar al agente ");
		//System.out.println(parametersMessage);
		try {
			flujoSalida.writeUTF(frame.getParametersMessage());
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
	}
	
	
	private class mouseListener implements MouseListener{

		@Override
		public void mouseClicked(MouseEvent ev) {
			x=ev.getX()-dx;
			y=ev.getY()-dy;
			
				switch(state){
				case Constants.WAIT_FOR_ACTION:
					if(ev.getButton() == MouseEvent.BUTTON3){
						//System.out.println("Click izquierdo");
					//	WorldObject obj = world.clickObject(ev.getX()-dx,ev.getY()-dy);
						try {
							String msg = Message.ASK_FOR_ACTION_FROM_OBJECT_INVENTORY+System.getProperty("line.separator")+getObjectID(x, y);
							flujoSalida.writeUTF(msg);
							System.out.println(msg);
						} catch (IOException e) {
							// TODO Auto-generated catch block
							e.printStackTrace();
						}
					}
					if(ev.getButton() == MouseEvent.BUTTON1){
						
						requestInventoryFromObject();
					}
					
				break;
				case Constants.PARAMETERS_FOR_ACTION:
					x=ev.getX()-dx;
					y=ev.getY()-dy;
					
					if(ev.getButton() == MouseEvent.BUTTON3){
						frame.setState(Constants.WAIT_FOR_ACTION);
						System.out.println("NO DOY PARAMETROS A LA ACCION");
						return;
					}
					System.out.println("Asigno Parametro");
					/*if(frame.getParametersStack().isEmpty()){
						sendParametersToAgent();
						state=Constants.WAIT_FOR_ACTION;
						return;
					}*/
					switch (frame.getParametersStack().pop()){
					case constants.Constants.PARAMETER_OBJECT:
						addObjectIdToParameterMessage(x,y);
					break;
			/*		case constants.Constants.PARAMETER_POSITION:
						addPositionToParameterMessage(x,y);
					break;*/
					}
					if(frame.getParametersStack().isEmpty()){
						frame.setState(Constants.WAIT_FOR_ACTION);
						
						sendParametersToAgent();
					}
				//	setParameter(ev.getX()-dx, ev.getY()-dy);
				break;
				}
		
			}


		@Override
		public void mouseEntered(MouseEvent e) {
			
			
		}

		@Override
		public void mouseExited(MouseEvent e) {
			// TODO Auto-generated method stub
			
		}

		@Override
		public void mousePressed(MouseEvent e) {
			// TODO Auto-generated method stub
			
		}

		@Override
		public void mouseReleased(MouseEvent e) {
			// TODO Auto-generated method stub
			
		}
		
	}
	
	private class mouseMotionListener implements MouseMotionListener {

		@Override
		public void mouseDragged(MouseEvent e) {
			// TODO Auto-generated method stub
			
		}

		@Override
		public void mouseMoved(MouseEvent e) {
			mouseY=e.getY();
			
		}
		
	}
	
}
